package Arrays;

import java.util.Arrays;

public class _621_TaskScheduler {
    //reference solution
    public int leastInterval(char[] tasks, int n) {
        int count = 0;
        int[] alphabet = new int[26];
        for (char c : tasks) {
            alphabet[c-'a']++;
        }
        Arrays.sort(alphabet);
        while (alphabet[25] > 0) {
            int i=0;
            // the circle count is n+1 so that when a new circle begin,the same task can satisfy the cool interval ask.
            while (i <=n) {
                if (alphabet[25] == 0) {
                    break;
                }
                if (i<26 && alphabet[25 - i] > 0) {
                    alphabet[25-i]--;
                }
                count++;
                i++;
            }
            Arrays.sort(alphabet);
        }
        return count;
    }
}
